package com.jstyle.jclife.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Scroller;

import com.jstyle.jclife.R;
import com.jstyle.jclife.utils.ScreenUtils;


public class DecimalScaleRulerView extends View {

    private int mMinVelocity;
    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;
    private int mWidth;
    private int mHeight;
    private Context context;
    private float mValue = 50;
    private float mMaxValue = 100;
    private float mMinValue = 0;
    private int mItemSpacing;
    private int mPerSpanValue = 1;
    private int mMaxLineHeight;
    private int mMiddleLineHeight;
    private int mMinLineHeight;
    private int mLineWidth;
    private int mTextMarginTop;
    private float mTextHeight;

    private Paint mTextPaint; // 绘制文本的画�?
    private Paint mLinePaint;
    private int mSelectWidth = 8;
    private int mSelectColor = Color.WHITE;
    private int mTotalLine;
    private int mMaxOffset;
    private float mOffset; // 默认尺起始点在屏幕中�?, offset是指尺起始点的偏移�??
    private int mLastX, mMove;
    private OnValueChangeListener mListener;
    private Paint mSelectPaint = new Paint();
    private int defaultWidth;
    private int defaultHeight;
    int mTextSize;
    int maxTextSize;
    Bitmap indicatorBitmap;
    private int indicatorBitmapHeight;
    private float zoomLevel=1;//小数
    public DecimalScaleRulerView(Context context) {
        this(context, null);
    }

    public DecimalScaleRulerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public DecimalScaleRulerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    protected void init(Context context) {
        this.context = context;
        indicatorBitmap= BitmapFactory.decodeResource(getResources(), R.drawable.goal_down);
        mScroller = new Scroller(context);
        indicatorBitmapHeight=indicatorBitmap.getHeight();
        mMinVelocity = ViewConfiguration.get(getContext()).getScaledMinimumFlingVelocity();
        mItemSpacing = ScreenUtils.dip2px(context, 14);
        mLineWidth = ScreenUtils.dip2px(context, 1);
        mMaxLineHeight = ScreenUtils.dip2px(context, 42);
        mMiddleLineHeight = ScreenUtils.dip2px(context, 31);
        mMinLineHeight = ScreenUtils.dip2px(context, 17);
        mTextMarginTop = ScreenUtils.dip2px(context, 11);
        defaultHeight = ScreenUtils.dip2px(context, 80);
        defaultWidth = ScreenUtils.dip2px(context, 200);
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextSize(ScreenUtils.sp2px(context, 16));
        mTextPaint.setColor(Color.WHITE);
        mTextHeight = ScreenUtils.getFontHeight(mTextPaint);

        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mLinePaint.setStrokeWidth(mLineWidth);
        mLinePaint.setColor(Color.parseColor("#2e5f79"));
    }

    public void setParam(int itemSpacing, int maxLineHeight, int middleLineHeight, int minLineHeight, int textMarginTop, int textSize) {
        mItemSpacing = ScreenUtils.dip2px(this.context,itemSpacing);
        mMaxLineHeight = ScreenUtils.dip2px(this.context,maxLineHeight);
        mMiddleLineHeight =ScreenUtils.dip2px(this.context, middleLineHeight);
        mMinLineHeight =ScreenUtils.dip2px( this.context,minLineHeight);
        mTextMarginTop = ScreenUtils.dip2px(this.context,textMarginTop);
        mTextSize=ScreenUtils.dip2px(this.context,textSize);
        maxTextSize=ScreenUtils.dip2px(this.context,15);
        mTextPaint.setTextSize(textSize);
    }


    public void initViewParam(float defaultValue, float minValue, float maxValue, int spanValue) {
        this.mValue = defaultValue;
        this.mMaxValue = maxValue;
        this.mMinValue = minValue;
        this.mPerSpanValue = spanValue;
        this.mTotalLine = (int) (maxValue - minValue) / spanValue + 1;
        mMaxOffset = -(mTotalLine - 1) * mItemSpacing;

        mOffset = (minValue - defaultValue) / spanValue * mItemSpacing;
        invalidate();
        setVisibility(VISIBLE);
    }

    /**
     * 设置用于接收结果的监听器
     *
     * @param listener
     */
    public void setValueChangeListener(OnValueChangeListener listener) {
        mListener = listener;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w > 0 && h > 0) {
            mWidth = w;
            mHeight = h;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
            height = defaultHeight;
        }
        if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
            width = defaultWidth;
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBackground(canvas);
        drawIndicator(canvas);
        drawLine(canvas);
       // drawMiddleLine(canvas);
        //drawValue(canvas);
    }

    private void drawIndicator(Canvas canvas) {

        float width=indicatorBitmap.getWidth();
        canvas.drawBitmap(indicatorBitmap,(mWidth-width)/2,0-indicatorBitmapHeight/4,mLinePaint);
    }

    private void drawBackground(Canvas canvas) {
        RectF rectF=new RectF();
        rectF.left=0;
        rectF.top=indicatorBitmapHeight/2;
        rectF.right=mWidth;
        rectF.bottom=mHeight;
        mLinePaint.setStyle(Paint.Style.STROKE);
        canvas.drawRect(rectF,mLinePaint);
    }

    private void drawLine(Canvas canvas) {
        float left, height;
        String value;
        int alpha;
        float scale;
        int srcPointX = mWidth / 2; // 默认表尺起始点在屏幕中心
        for (int i = 0; i < mTotalLine; i++) {
            left = srcPointX + mOffset + i * mItemSpacing;

            if (left < 0) continue;
            if (left > mWidth) break;
//            if (left < 0 || left > mWidth) {
//                continue;
//            }
            value = String.valueOf((int) (mMinValue + i * mPerSpanValue));
            if (Integer.valueOf(value) % (10 *mPerSpanValue)== 0) {
                height = mMaxLineHeight;
            } else if (Integer.valueOf(value)  % (5*mPerSpanValue) == 0) {
                height = mMiddleLineHeight;
            } else {
                height = mMinLineHeight;
            }
            scale = 1 - Math.abs(left - srcPointX) / srcPointX;

            alpha = (int) (255 * scale * scale);
          //  mLinePaint.setAlpha(alpha);
            canvas.drawLine(left, indicatorBitmapHeight/2 ,
                    left, height+indicatorBitmapHeight/2, mLinePaint);
            if (Integer.valueOf(value) % (10 *mPerSpanValue) == 0 ) { // 大指�?,要标注文�?
                //mTextPaint.setAlpha(alpha);
                mTextPaint.setColor(left==mWidth/2?Color.WHITE:Color.parseColor("#999999"));
                mTextPaint.setTextSize(left==mWidth/2?maxTextSize: mTextSize);
                int realValue= (int) (Integer.valueOf(value)*zoomLevel);
                String drawValue= String.valueOf(realValue);
                canvas.drawText(drawValue, left - mTextPaint.measureText(drawValue) / 2,
                        height+indicatorBitmapHeight/2 +ScreenUtils.dip2px(context, 16), mTextPaint);
            }

        }
    }

    private void drawValue(Canvas canvas) {
        // TODO Auto-generated method stub
        mSelectPaint.setTextSize(ScreenUtils.dip2px(context, 18));
        mSelectPaint.setAntiAlias(true);
        canvas.drawText((int) mValue + "", mWidth / 2 + ScreenUtils.dip2px(context, 5), mHeight, mSelectPaint);
    }

    private void drawMiddleLine(Canvas canvas) {
        canvas.save();

        mSelectPaint.setStrokeWidth(mSelectWidth);
        mSelectPaint.setColor(mSelectColor);
        canvas.drawLine(mWidth / 2, 0, mWidth / 2, mHeight, mSelectPaint);
        canvas.restore();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        int xPosition = (int) event.getX();

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mScroller.forceFinished(true);
                mLastX = xPosition;
                mMove = 0;
                break;
            case MotionEvent.ACTION_MOVE:
                mMove = (mLastX - xPosition);
             //   mScroller.startScroll(mLastX,0,mMove,0);
               changeMoveAndValue();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                countMoveEnd();
                countVelocityTracker();
                return false;
            // break;
            default:
                break;
        }

        mLastX = xPosition;
        return true;
    }

    private void countVelocityTracker() {
        mVelocityTracker.computeCurrentVelocity(1000);
        float xVelocity = mVelocityTracker.getXVelocity();
        if (Math.abs(xVelocity) > mMinVelocity) {
            mScroller.fling(0, 0, (int) xVelocity, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
        }
    }

    private void countMoveEnd() {
        mOffset -= mMove;
        if (mOffset <= mMaxOffset) {
            mOffset = mMaxOffset;
        } else if (mOffset >= 0) {
            mOffset = 0;
        }

        mLastX = 0;
        mMove = 0;

        mValue = mMinValue + Math.round(Math.abs(mOffset) * 1.0f / mItemSpacing) * mPerSpanValue / 1.0f;
        mOffset = (mMinValue - mValue) * 1.0f / mPerSpanValue * mItemSpacing; // 矫正位置,保证不会停留在两个相邻刻度之�?
        notifyValueChange();
        postInvalidate();
    }

    private void changeMoveAndValue() {
        mOffset -= mMove;
        if (mOffset <= mMaxOffset) {
            mOffset = mMaxOffset;
            mMove = 0;
            mScroller.forceFinished(true);
        } else if (mOffset >= 0) {
            mOffset = 0;
            mMove = 0;
            mScroller.forceFinished(true);
        }
        mValue = mMinValue + Math.round(Math.abs(mOffset) * 1.0f / mItemSpacing) * mPerSpanValue / 1.0f;
        notifyValueChange();
        postInvalidate();
    }

    private void notifyValueChange() {
        if (null != mListener) {
            mListener.onValueChange(mValue);
        }
    }

    public interface OnValueChangeListener {
        void onValueChange(float value);
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            if (mScroller.getCurrX() == mScroller.getFinalX()) { // over
                countMoveEnd();
            } else {
                int xPosition = mScroller.getCurrX();

                mMove = (mLastX - xPosition);
                changeMoveAndValue();
                mLastX = xPosition;
            }
        }
    }
    public void setZoomLevel(float zoomLevel){
        this.zoomLevel=zoomLevel;
    }
}
